package com.doctor.windflower_doctor.util;

import java.io.File;
import java.io.IOException;

import com.doctor.windflower_doctor.delegate.PlayAudio;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;

/**
 * <p>
 * 功能
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年11月17日 下午3:12:22
 * @version 1.0 </br> 最后修改人 无
 * 
 */
public class PlayManager implements OnBufferingUpdateListener, OnCompletionListener, MediaPlayer.OnPreparedListener {
	public MediaPlayer mediaPlayer;
	private PlayAudio audio;
	private String currentVideoUrl;

	public PlayManager() {
		try {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnBufferingUpdateListener(this);
			mediaPlayer.setOnPreparedListener(this);
			mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e) {
			LogUtils.e("mediaPlayer", "error", e);
		}
	}

	public void play() {
		mediaPlayer.start();
	}

	public void playUrl(String videoUrl) {
		try {
			if (mediaPlayer.isPlaying()) {
				if (videoUrl.equals(currentVideoUrl)) {
					pauseManager();
					return;
				} else {
					stopManager();
					return;
				}
			}
			currentVideoUrl = videoUrl;
			mediaPlayer.reset();
			File file = new File(videoUrl);
			LogUtils.e("=====file=======" + file.exists());
			mediaPlayer.setDataSource(videoUrl);
			mediaPlayer.prepare();// prepare之后自动播放
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void pauseManager() {
		LogUtils.e("==========pause===========");
		if (audio != null)
			audio.audioStop(true);
		mediaPlayer.pause();
		// mediaPlayer.reset();
	}

	public void stopManager() {
		LogUtils.e("==========stop===========");
		if (audio != null)
			audio.audioStop(true);
		mediaPlayer.stop();
		// mediaPlayer.reset();
	}

	public boolean isPlay() {
		return mediaPlayer.isPlaying();
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		LogUtils.e("==========pause===========");
		if (audio != null)
			audio.audioPlay(true);
		arg0.start();
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		LogUtils.e("============onCompletion==============");
		currentVideoUrl = null;
		stopManager();
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1) {

	}

	public void setPlayAudio(PlayAudio audio) {
		this.audio = audio;
	}
}
